package org.zxyj.system.server.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zxyj.core.service.AbstractBaseServiceImpl;
import org.zxyj.system.dao.IRoleDao;
import org.zxyj.system.dao.IRoleResourceDao;
import org.zxyj.system.domain.Role;
import org.zxyj.system.domain.RoleResource;
import org.zxyj.system.server.IRoleService;

/**
 * @author zhaoyong
 * @version 2016年2月25日
 */
@Service
public class RoleServiceImpl extends AbstractBaseServiceImpl<IRoleDao, Role>implements IRoleService {

	@Autowired
	private IRoleResourceDao roleResourceDao;

	@Override
	public Role findEntity(Map<String, Object> criteria) {
		logger.debug("find role refer to criteria, param: criteria[{}]", criteria);

		if (null == criteria) {
			// 参数错误
			return null;
		}
		return dao.findById(criteria);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void persistentEntity(Role role) {
		super.persistentEntity(role);

		// 持久化处理角色权限
		this.persistentRoleResource(role);
	}

	/**
	 * 持久化处理角色权限
	 * 
	 * @param role
	 */
	private void persistentRoleResource(Role role) {
		if (null != role && null != role.getId()) {
			// 删除该角色下所有的权限
			Map<String, Object> criteria = new HashMap<String, Object>();
			criteria.put("role", role);
			roleResourceDao.delete(criteria);

			List<RoleResource> roleResources = role.getRoleResources();
			if (!CollectionUtils.isEmpty(roleResources)) {
				List<RoleResource> tempRoleResources = new ArrayList<RoleResource>();
				for (RoleResource roleResource : roleResources) {
					if (roleResource.getResource() == null) {
						continue;
					}
					roleResource.setRole(role);
					tempRoleResources.add(roleResource);
				}
				roleResourceDao.batchInsert(tempRoleResources);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteEntity(Map<String, Object> criteria) {
		logger.debug("deleting role from DB, param: criteria[{}]", criteria);

		if (!MapUtils.isEmpty(criteria)) {
			// 级联删除角色权限
			List<Role> roles = this.listEntities(criteria);
			if (!CollectionUtils.isEmpty(roles)) {
				Map<String, Object> deleteCriteria = new HashMap<String, Object>();
				deleteCriteria.put("roles", roles);
				roleResourceDao.delete(deleteCriteria);

				dao.delete(criteria);
			}
		}
	}

}